package club.caihappy.admin.controller;

import club.caihappy.admin.bean.Account;
import club.caihappy.admin.bean.City;
import club.caihappy.admin.bean.User;
import club.caihappy.admin.service.impl.AccountServiceImpl;
import club.caihappy.admin.service.impl.CityServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * Created by DELL on 2021/11/11
 **/
@Slf4j
@Controller
public class IndexController {

    @Autowired
    AccountServiceImpl accountService;
    @Autowired
    CityServiceImpl cityService;

    @ResponseBody
    @PostMapping("/saveCity")
    public City saveCity(City city) {
        cityService.saveCity(city);
        return city;
    }

    @ResponseBody
    @GetMapping("/acct")
    public Account getAccountById(@RequestParam("id") Long id) {
        return accountService.getAccountById(id);
    }

    @ResponseBody
    @GetMapping("/city")
    public City getCityById(@RequestParam("id") Long id) {
        return cityService.getById(id);
    }


    /**
     * 来登录页
     *
     * @return
     */
    @GetMapping(value = {"/", "/login"})
    public String loginPage() {
        return "login";
    }

    @PostMapping("/login")
    public String main(User user, HttpSession session, Model model) {
        System.out.println(user);
        if (!StringUtils.isEmpty(user.getUserName()) && "123".equals(user.getPassword())) {
            //把登录成功的用户保存起来
            session.setAttribute("loginUser", user);
            //登陆成功重定向到main.html
            return "redirect:/main.html";
        } else {
            model.addAttribute("msg", "账号密码错误");
            return "login";
        }
    }

    /**
     * 去main页面
     *
     * @return
     */
    @GetMapping("/main.html")
    public String mainPage(Model model, HttpSession session) {
        log.info("当前方法是:{}", "mainPage");
//        int i=10/0;
//        Object loginUser = session.getAttribute("loginUser");
//        if (loginUser != null) {
//            return "main";
//        } else {
//            model.addAttribute("msg", "请重新登录");
//            return "login";
//        }
        return "main";
    }

    @Autowired
    JdbcTemplate jdbcTemplate;

    @ResponseBody
    @GetMapping("/sql")
    public String queryFromDB() {
        Long res = jdbcTemplate.queryForObject("select count(*) from tbl_user", long.class);
        return res.toString();
    }

}
